package pri.controller;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import pri.pojo.SaleData;
import pri.pojo.SalePercent;
import pri.service.order.OrderService;
import pri.service.product.ProductService;
import pri.service.statistics.StatisticsService;

import java.util.Collections;
import java.util.Date;
import java.util.List;
@Controller
public class statisticsController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private StatisticsService statisticsService;
    @Autowired
    private ProductService productService;

    @RequestMapping("/doStatistics")
    public String doStatistics(ModelMap modelMap) {

        Date date = DateUtil.date();   //获取当前时间
        Date newdate = DateUtil.offset(date, DateField.MONTH, -3);

        List<SaleData> saleDatas = orderService.getSale(newdate, date);
        Collections.sort(saleDatas, (o1, o2) -> Integer.parseInt(o2.getCount()) - Integer.parseInt(o1.getCount()));  //按销量排序

        //销售总量
        int totalSaleNum = 0;
        for (SaleData sd : saleDatas) {
            totalSaleNum += Integer.parseInt(sd.getCount());
        }
        modelMap.put("sales", totalSaleNum);

        //浏览量
        int browNum=productService.allBrow();
        modelMap.put("browNum",browNum);

        //订单量
        int orders = orderService.getOrderNum(newdate, date);
        modelMap.put("orders", orders);

        //销售占比
        if (saleDatas != null) {
            List<SalePercent> salePercents = statisticsService.getSalePercents(saleDatas, totalSaleNum);
            modelMap.put("salePercents", salePercents);
            System.out.println(salePercents);

            int i = 1;

            for (SalePercent sp : salePercents) {
                if (i > 5) break;
                modelMap.put("sp" + i, sp);
                i++;
            }

            if (saleDatas.size() > 5) {

                int j = 1,topfive=0;
                for (SaleData sd : saleDatas) {
                    if (j > 5) break;
                    topfive += Integer.parseInt(sd.getCount());
                    j++;
                }

                modelMap.put("other",String.format("%.0f",(1.0*(totalSaleNum-topfive)/totalSaleNum)*100)+"%");
            }
        }


        return "back/discount/statistics";
    }
}
